import numpy as np
import scipy.io.wavfile as wavfile
from ctypes import *
import pandas as pd
from  glob import glob
import os
import librosa
import python_speech_features as psf
from tqdm import tqdm
import time

def audio_mfcc(sig,rate,videorate = 30,numcep = 13):

    winlen=1./videorate
    winstep=0.48/videorate
    winfunc=np.hanning

    mfcc=psf.mfcc(sig,rate,winlen=winlen,winstep=winstep,numcep=numcep,nfilt=numcep*2,nfft=int(rate/videorate),winfunc=winfunc)
    #print('------------mfcc.shape',mfcc.shape)
    mfcc_delta=psf.base.delta(mfcc,2)
    mfcc_delta2=psf.base.delta(mfcc_delta,2)
    mfcc_all=np.concatenate((mfcc,mfcc_delta,mfcc_delta2),axis=1)
   
    return mfcc_all


def audio_mfcc_file(wavpath,fps = 30): 
    
    start_time = time.time()  
    sig,rate=librosa.load(wavpath,sr=16000)
    
    frame_per_second=fps
    chunks_lenght=260
    audio_framenum=int(len(sig)/rate*frame_per_second)

    a=np.zeros(chunks_lenght*rate//1000,dtype=np.int16)
    signal=np.hstack((a,sig,a))

    frames_step=1000.0/frame_per_second
    rate_HKZ=int(rate/1000)

    audio_frames=[signal[int(i*frames_step*rate_HKZ):int((i*frames_step+chunks_lenght*2)*rate_HKZ)] for i in range(audio_framenum)]

    features = None

    for i in range(len(audio_frames)):
        feature = audio_mfcc(audio_frames[i],rate,fps)
        if features is None:
            features = np.expand_dims(feature,0)
        else:
            features = np.concatenate([features,np.expand_dims(feature,0)],0)
    
    past_time = time.time() - start_time
    print(f"mfcc file: {wavpath} feature size:{features.shape} cost time:{past_time}")
    return features


if __name__ == '__main__':
    #audioProcess(path='/data/xtx/yanghan/thirdtool/Audio2BS/data/train_val',outdata_dir='/data/xtx/yanghan/thirdtool/Audio2BS/data/train_val_feature_blendshape')
    # audioTestProcess(path='/data/xtx/yanghan/thirdtool/Audio2BS/data/test-B/audio_for_B/all_test_B',outdata_dir='/data/xtx/yanghan/thirdtool/Audio2BS/data/test-B/audio_for_B/all_test_B_output')
     
    projroot = os.path.join(os.path.dirname(__file__),'../')
    wavpath = os.path.join(projroot,'data/test/woman.wav')
    audio_mfcc_file(wavpath)
    